package com.ruoyi.merchandise.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.merchandise.domain.MemberCardImport;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.merchandise.domain.MemberCard;
import com.ruoyi.merchandise.service.IMemberCardService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 卡密管理Controller
 * 
 * @author 李文保
 * @date 2025-03-12
 */
@RestController
@RequestMapping("/merchandise/card")
public class MemberCardController extends BaseController
{
    @Autowired
    private IMemberCardService memberCardService;

    /**
     * 查询卡密管理列表
     */
    @PreAuthorize("@ss.hasPermi('merchandise:card:list')")
    @GetMapping("/list")
    public TableDataInfo list(MemberCard memberCard)
    {
        startPage();
        List<MemberCard> list = memberCardService.selectMemberCardList(memberCard);
        return getDataTable(list);
    }

    /**
     * 导出卡密管理列表
     */
    @PreAuthorize("@ss.hasPermi('merchandise:card:export')")
    @Log(title = "卡密管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MemberCard memberCard)
    {
        List<MemberCard> list = memberCardService.selectMemberCardList(memberCard);
        ExcelUtil<MemberCard> util = new ExcelUtil<MemberCard>(MemberCard.class);
        util.exportExcel(response, list, "卡密管理数据");
    }

    /**
     * 获取卡密管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('merchandise:card:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(memberCardService.selectMemberCardById(id));
    }

    /**
     * 新增卡密管理
     */
    @PreAuthorize("@ss.hasPermi('merchandise:card:add')")
    @Log(title = "卡密管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MemberCard memberCard)
    {
        return toAjax(memberCardService.insertMemberCard(memberCard));
    }

    /**
     * 修改卡密管理
     */
    @PreAuthorize("@ss.hasPermi('merchandise:card:edit')")
    @Log(title = "卡密管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MemberCard memberCard)
    {
        return toAjax(memberCardService.updateMemberCard(memberCard));
    }

    /**
     * 删除卡密管理
     */
    @PreAuthorize("@ss.hasPermi('merchandise:card:remove')")
    @Log(title = "卡密管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(memberCardService.deleteMemberCardByIds(ids));
    }


    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('merchandise:card:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<MemberCard> util = new ExcelUtil<MemberCard>(MemberCard.class);
        List<MemberCard> cardsList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        if (StringUtils.isNull(cardsList) || cardsList.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        for(int i = 0;i<cardsList.size();i++){
            MemberCard card = cardsList.get(i);
            int num = memberCardService.insertMemberCard(cardsList.get(i));
            if(num==1){
                successNum++;
                successMsg.append("<br/>" + successNum + "、卡密 " + card.getCode() + " 导入成功");
            }else{
                failureNum++;
                String msg = "<br/>" + failureNum + "、卡密 " + card.getCode() + " 导入失败：";
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return success(successMsg.toString());
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<MemberCardImport> util = new ExcelUtil<MemberCardImport>(MemberCardImport.class);
        util.importTemplateExcel(response, "卡密数据");
    }
}
